<template>
  <div class="player" v-show="playlist.length > 0" @click.stop >
    <transition name="normal"
      @enter="enter"
      @after-enter="afterEnter"
      @leave="leave"
      @after-leave="afterLeave"
    >
      <div class="normal-player" v-show="fullScreen">
        <div class="background">
          <img width="100%" height="100%" :src="currentSong.image">
        </div>
        <div class="top">
          <div class="back" @click="back">
            <i class="icon-back"></i>
          </div>
          <h1 class="title" v-html="currentSong.name"></h1>
          <h2 class="subtitle" v-html="currentSong.singer"></h2>
        </div>
        <div class="middle"
          @touchstart.prevent="middleTouchStart"
          @touchmove.prevent="middleTouchMove"
          @touchend="middleTouchEnd"
        >
        <div class="middle-l" ref="middleL">
          <div class="cd-wrapper" ref="cdWrapper">
            <div class="cd" :class="cdCls">
              <img class="image" :src="currentSong.image">
            </div>
          </div>
          <div class="playing-lyric-wrapper">
            <div class="playing-lyric">{{playingLyric}}</div>
          </div>
        </div>
        <scroll ref="lyricList" class="middle-r" :click="scrollClick" :data="currentLyric && currentLyric.lines">
          <div class="lyric-wrapper">
            <div v-if="currentLyric">
              <p
                ref="lyricLine"
                class="text"
                v-for="(line, index) in currentLyric.lines"
                :class="{active: currentLineNum === index}"
                :key="index" >{{line.txt}}</p>
            </div>
          </div>
        </scroll>
      </div>
      <div class="bottom">
        <div class="dot-wrapper">
          <span class="dot" :class="{'active':currentShow==='cd'}"></span>
          <span class="dot" :class="{'active':currentShow==='lyric'}"></span>
        </div>
        <div class="progress-wrapper">
          <span class="time time-l">{{formateMiSs(currentTime)}}</span>
          <div class="progress-bar-wrapper">
            <progress-bar @percentChange="handlePercentChange" :percent="percent"></progress-bar>
          </div>
          <span class="time time-r">{{formateMiSs(duration)}}</span>
        </div>
        <div class="operators">
          <div @click="changePlayMode" class="icon i-left">
            <i :class="modeIcon"></i>
          </div>
          <div class="icon i-left" :class="displayCls">
            <i class="icon-prev" @click="prev"></i>
          </div>
          <div class="icon i-center" :class="displayCls">
            <i :class="playIcon" @click="togglePlaying"></i>
          </div>
          <div class="icon i-right" :class="displayCls">
            <i class="icon-next" @click="next"></i>
          </div>
          <div class="icon i-right">
            <i :class="getFavoriteIcon(currentSong)" @click.stop="toggleFavorite(currentSong)"></i>
          </div>
        </div>
      </div>
    </div>
    </transition>
    <transition name="mini">
      <div class="mini-player" v-show="!fullScreen" @click="open">
        <div class="icon" >
          <img width="40" height="40" :class="cdCls" :src="currentSong.image">
        </div>
        <div class="text">
          <h2 class="name">{{currentSong.name}}</h2>
          <p class="desc">{{currentSong.singer}}</p>
        </div>
        <div class="control">
          <progress-circle :radius="radius" :percent="percent">
            <i @click.stop="togglePlaying" :class="miniIcon" class="icon-mini"></i>
          </progress-circle>
        </div>
        <div class="control">
          <i class="icon-playlist" @click.stop="showPlaylist"></i>
        </div>
      </div>
    </transition>
    <play-list ref="playlist"></play-list>
    <audio ref="audio" @timeupdate="handleCurrentTime" @canplay ="canPlay" @play="ready" @error="error" @ended="handleEnded"></audio>
  </div>
</template>

<script type="text/ecmascript-6">
import animations from 'create-keyframe-animation'
// import * as _ from 'lodash'
import Lyric from 'lyric-parser'

import { mapGetters, mapMutations, mapActions } from 'vuex'
import * as types from '@/store/mutations-types'
import { prefixStyle } from 'common/js/dom'
import { getPlayUrlIp } from 'api/song'
import { formateMiSs } from 'common/js/tool'
import progressBar from 'base/progress-bar/progress-bar'
import ProgressCircle from 'base/progress-circle/progress-circle'
import { playMode } from 'common/js/config'
import Scroll from 'base/scroll/scroll'
import PlayList from 'components/play-list/play-list'
import { mixinPlayMode } from 'common/js/mixin'

const transform = prefixStyle('transform')
// const transitionDuration = prefixStyle('transitionDuration')

export default {
  name: 'player',
  mixins: [ mixinPlayMode ],
  data() {
    return {
      radius: 32,
      duration: '',
      currentTime: '',
      songReady: false,
      freeflowsip: {
        type: Array,
        /* eslint-disable */
        default: [
          'http://123.157.255.145/amobile.music.tc.qq.com/',
          'http://123.157.255.146/amobile.music.tc.qq.com/',
          'http://123.157.255.147/amobile.music.tc.qq.com/'
        ]
      },
      currentLyric: null,
      currentLineNum: -1,
      scrollClick: true,
      currentShow: 'cd',
      playingLyric: ''
    }
  },
  components: {
    progressBar,
    ProgressCircle,
    Scroll,
    PlayList
  },
  methods: {
    showPlaylist() {
      this.$refs.playlist.show()
    },
    getLyric() {
      this.currentSong.getLyric().then((res) => {
        if (this.currentLyric) {
          this.currentLyric.stop()
          this.currentLyric = null
          this.currentLineNum = 0
          this.playingLyric = ''
        }
        this.currentLyric = new Lyric(res, this.handleLyric)
        this.currentLyric.play()
      }).catch(() => {
        if (this.currentLyric) {
          this.currentLyric.stop()
          this.currentLyric = null
          this.currentLineNum = 0
          this.playingLyric = ''
        }
      })
    },
    middleTouchStart(e) {
      this.touch.touchFlag = true
      // 用来判断是否是一次移动
      this.touch.moved = false
      this.touch.startX = e.touches[0].pageX
      this.touch.startY = e.touches[0].pageY
    },
    middleTouchMove(e) {
      if (!this.touch.touchFlag) return
      const touch = e.touches[0]
      // 移动歌词 lyricList 的 transform
      // lyricList最大偏移位置
      let minLeft = - window.innerWidth
      // lyricList最小偏移位置
      let maxLeft = 0
      let deltaX = touch.pageX - this.touch.startX
      let deltaY = touch.pageY - this.touch.startY
      // Y轴的偏移量更多的话，认为用户是在上下拖动歌词，而非切换歌词窗口
      if ((Math.abs(deltaY) - Math.abs(deltaX)) > 0) {
        return
      }
      this.touch.moved = true
      let initLeft = this.currentShow === 'cd' ? 0 : minLeft
      let offsetLeft = Math.min(maxLeft,Math.max(minLeft, deltaX + initLeft))
      this.touch.percent = Math.abs(offsetLeft) / window.innerWidth
      this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetLeft}px,0,0)`
      this.$refs.lyricList.$el.style['transition'] = `transform 0s`
      this.$refs.middleL.style['transition'] = ''
      let middleOpacity = 1 - this.touch.percent
      this.$refs.middleL.style.opacity = `${middleOpacity}`
    },
    middleTouchEnd() {
      if (!this.touch.moved)  return
      let minLeft = - window.innerWidth
      let maxLeft = 0
      let offset = null
      let middleOpacity = 1
      if (this.currentShow == 'cd') {
        offset = maxLeft
        if (this.touch.percent > 0.1) {
          this.currentShow = 'lyric'
          offset = minLeft
        }
      } else {
        offset = minLeft
        if (this.touch.percent < 0.9) {
          offset = maxLeft
          this.currentShow = 'cd'
        }
      }
      if (offset === minLeft) {
        middleOpacity = 0
      } else {
        middleOpacity = 1
      }

      this.$refs.lyricList.$el.style['transition'] = `transform .5s`
      this.$refs.lyricList.$el.style[transform] = `translate3d(${offset}px,0,0)`
      this.$refs.middleL.style['transition'] = 'opacity .5s'
      this.$refs.middleL.style.opacity = `${middleOpacity}`
      this.touch.touchFlag = false
    },
    handleLyric({lineNum, txt}) {
      if (lineNum === 0) {
        let el = this.$refs.lyricLine[lineNum]
        this.$refs.lyricList.scrollToElement(el, 1000)
      }
      this.playingLyric = txt
      this.currentLineNum = lineNum
      if (lineNum > 5) {
        let el = this.$refs.lyricLine[lineNum - 5]
        this.$refs.lyricList.scrollToElement(el, 1000)
      }
    },
    // changePlayMode() {
    //   let newMode = (this.mode + 1) % 3
    //   this.setPlayMode(newMode)
    //   if (playMode.random === newMode) {
    //     let currentSongId = this.currentSong.id
    //     const newPlayinglist = shuffle(this.sequenceList)
    //     this.setPlayList(newPlayinglist)
    //     let newCurrentIndex = _.findIndex(newPlayinglist, function(o) { return o.id === currentSongId })
    //     this.setCurrentIndex(newCurrentIndex)
    //   }
    // },
    handlePercentChange(percent) {
      const newCurrentTime = percent * this.duration
      this.$refs.audio.currentTime = newCurrentTime
      if (!this.playing) {
        this.setPlayingState(true)
      }
      if (this.currentLyric) {
        this.currentLyric.seek(newCurrentTime * 1000)
      }
    },
    handleCurrentTime(e) {
      this.currentTime = e.target.currentTime
    },
    handleEnded() {
      if (this.mode === playMode.loop) {
        this._loop()
      } else {
        this.next()
      }
    },
    _loop() {
      this.$refs.audio.currentTime = 0
      this.$refs.audio.play()
      this.setPlayingState(true)
      if (this.currentLyric) {
        this.currentLyric.seek(0)
        this.currentLineNum = 0
      }
    },
    canPlay() {
      this.duration = this.$refs.audio.duration
    },
    ready() {
      this.songReady = true
      this.saveSong(this.currentSong)
    },
    error() {
      this.songReady = true
    },
    prev() {
      // 当前的歌曲没有准备好播放就不让切换到下一首
      if (!this.songReady) return

      if (this.playlist.length === 1) {
        this._loop()
      } else {
        let prevIndex = this.currentIndex - 1
        if (prevIndex === -1) {
          prevIndex = this.playlist.length - 1
        }
        this.setCurrentIndex(prevIndex)
        this.songReady = false
      }
    },
    next() {
      if (!this.songReady) return
      if (this.playlist.length === 1) {
        this._loop()
      } else {
        let nextIndex = this.currentIndex + 1
        if (nextIndex === (this.playlist.length -1) ) {
          nextIndex = 0
        }
        this.setCurrentIndex(nextIndex)
        this.songReady = false
      }
    },
    togglePlaying() {
      this.setPlayingState(!this.playing)
      if (this.currentLyric) this.currentLyric.togglePlay()
    },
    back() {
      this.setFullScreen(false)
    },
    open() {
      this.setFullScreen(true)
    },
    enter(el, done) {
      const {x, y, scale} = this._getPosAndScale()
      let animation = {
        0: {
          transform: `translate3d(${x}px,${y}px,0) scale(${scale})`
        },
        60: {
          transform: `translate3d(0,0,0) scale(1.1)`
        },
        100: {
          transform: `translate3d(0,0,0) scale(1)`
        }
      }
      animations.registerAnimation({
        name: 'move',
        animation,
        presets: {
          duration: 800,
          easing: 'linear'
        }
      })
      animations.runAnimation(this.$refs.cdWrapper, 'move', done)
    },
    afterEnter() {
      animations.unregisterAnimation('move')
      this.$refs.cdWrapper.style.animation = ''
    },
    leave(el, done) {
      this.$refs.cdWrapper.style.transition = 'all 0.4s'
      const {x, y, scale} = this._getPosAndScale()
      this.$refs.cdWrapper.style[transform] = `translate3d(${x}px,${y}px,0) scale(${scale})`
      // this._fundone = done
      this.$refs.cdWrapper.addEventListener('transitionend', done)
    },
    afterLeave() {
      // this.$refs.cdWrapper.removeEventListener('transitionend', this._fundone)
      this.$refs.cdWrapper.style.transition = ''
      this.$refs.cdWrapper.style[transform] = ''
    },
    ...mapMutations({
      setFullScreen: types.SET_FULL_SCREEN,
      setPlayingState: types.SET_PLAYING_STATE
    }),
    ...mapActions({
      saveSong: 'saveSong'
    }),
    _getPosAndScale() {
      const targetWidth = 40
      const paddingLeft = 40
      const paddingBottom = 30
      const paddingTop = 80
      const width = window.innerWidth * 0.8
      const scale = targetWidth / width
      const x = -(window.innerWidth / 2 - paddingLeft)
      const y = window.innerHeight - paddingTop - width / 2 - paddingBottom
      return {
        x,
        y,
        scale
      }
    }
  },
  computed: {
    percent() {
      if (this.duration > 0 && this.currentTime) {
        return this.currentTime / this.duration
      } else {
        return null
      }
    },
    displayCls() {
      return this.songReady ? '' : 'disable'
    },
    cdCls() {
      return this.playing ? 'play' : 'play pause'
    },
    playIcon() {
      return this.playing ? 'icon-pause' : 'icon-play'
    },
    miniIcon() {
      return this.playing ? 'icon-pause-mini' : 'icon-play-mini'
    },
    ...mapGetters({
      fullScreen: 'fullScreen',
      playing: 'playing'
    })
  },
  created() {

    getPlayUrlIp().then((resp) => {
      if (resp.req) {
        this.freeflowsip = resp.req.data.freeflowsip
      }
    })
    this.formateMiSs = formateMiSs // 格式化时间的方法
    this.touch = {}
  },
  watch: {
    currentSong(newSong, oldSong) {
      if (!newSong.id) return
      if (newSong.id === oldSong.id ) return
      // 获取歌曲真实播放地址
      if (newSong.mid) {
        newSong.getUrl(newSong.mid).then((purl) => {
          this.$refs.audio.src = this.freeflowsip[0] + purl
          setTimeout(() => { //
            this.setPlayingState(true)
            this.$refs.audio.play()
            // 获取歌词
            this.getLyric()
          }, 500)
        })
      }
    },
    playing(newPlaying) {
      const audio = this.$refs.audio
      this.$nextTick(() => {
        if (newPlaying) {
          audio.play()
        } else {
          audio.pause()
        }
      })
    }
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
@import '~common/stylus/variable'

.player
  .normal-player
    position: fixed
    left: 0
    right: 0
    top: 0
    bottom: 0
    z-index: 150
    background: $color-background
    .background
      position: absolute
      left: 0
      top: 0
      width: 100%
      height: 100%
      z-index: -1
      opacity: 0.6
      filter: blur(20px)
    .top
      position: relative
      margin-bottom: 25px
      .back
        position absolute
        top: 0
        left: 6px
        z-index: 50
        .icon-back
          display: block
          padding: 9px
          font-size: $font-size-large-x
          color: $color-theme
          transform: rotate(-90deg)
      .title
        width: 70%
        margin: 0 auto
        line-height: 40px
        text-align: center
        no-wrap()
        font-size: $font-size-large
        color: $color-text
      .subtitle
        line-height: 20px
        text-align: center
        font-size: $font-size-medium
        color: $color-text
    .middle
      position: fixed
      width: 100%
      top: 80px
      bottom: 170px
      white-space: nowrap
      font-size: 0
      .middle-l
        display: inline-block // 因为左划 显示完整歌词，所以需要inline-block
        vertical-align: top
        position: relative
        width: 100%
        height: 0
        padding-top: 80%
        .cd-wrapper
          position: absolute
          left: 10%
          top: 0
          width: 80%
          height: 100%
          .cd
            width: 100%
            height: 100%
            box-sizing: border-box
            border: 10px solid rgba(255, 255, 255, 0.1)
            border-radius: 50%
            &.play
              animation: rotate 20s linear infinite
            &.pause
              animation-play-state: paused
            .image
              position: absolute
              left: 0
              top: 0
              width: 100%
              height: 100%
              border-radius: 50%

        .playing-lyric-wrapper
          width: 80%
          margin: 30px auto 0 auto
          overflow: hidden
          text-align: center
          .playing-lyric
            height: 20px
            line-height: 20px
            font-size: $font-size-medium
            color: $color-text-l
      .middle-r
        display: inline-block // 因为左划 显示完整歌词，所以需要inline-block
        vertical-align: top
        width: 100%
        height: 100%
        overflow: hidden
        .lyric-wrapper
          width: 80%
          margin: 0 auto
          overflow: hidden
          text-align: center
          .text
            line-height: 32px
            color: $color-text-l
            font-size: $font-size-medium
            &.active
              color: $color-text
    .bottom
      position: absolute
      bottom: 50px
      width: 100%
      .dot-wrapper
        text-align: center
        font-size: 0
        .dot
          display: inline-block
          vertical-align: middle
          margin: 0 4px
          width: 8px
          height: 8px
          border-radius: 50%
          background: $color-text-l
          &.active
            width: 20px
            border-radius: 4px
            background: $color-text-ll
      .progress-wrapper
        display: flex
        align-items: center
        width: 80%
        margin: 0px auto
        padding: 10px 0
        .time
          flex: 0 0 35px
          line-height: 30px
          width: 35px
          color: $color-text
          font-size: $font-size-small
          &.time-l
            text-align: left
          &.time-r
            text-align: right
        .progress-bar-wrapper
          flex: 1

      .operators
        display: flex
        align-items: center
        .icon
          flex: 1
          color: $color-theme
          &.disable
            color: $color-theme-d
          i
            font-size: 30px
        .i-left
          text-align: right
        .i-center
          padding: 0 20px
          text-align: center
          i
            font-size: 40px
        .i-right
          text-align: left
        .icon-favorite
          color: $color-sub-theme

    &.normal-enter-active, &.normal-leave-active
      transition: all 0.4s
      .top, .bottom
        transition: all 0.4s cubic-bezier(0.86, 0.18, 0.82, 1.32)
    &.normal-enter, &.normal-leave-to
      opacity: 0
      .top
        transform: translate3d(0, -100px, 0)
      .bottom
        transform: translate3d(0, 100px, 0)
  .mini-player
    display: flex
    align-items: center
    position: fixed
    left: 0
    bottom: 0
    z-index: 180
    width: 100%
    height: 60px
    background: $color-highlight-background
    .icon
      flex: 0 0 40px
      width: 40px
      padding: 0 10px 0 20px
      &.disable
        color: $color-theme-d
      img
        border-radius: 50%
        &.play
          animation: rotate 10s linear infinite
        &.pause
          animation-play-state: paused

    &.mini-enter-active, &.mini-leave-active
      transition: all .4s
    &.mini-enter, &.mini-leave-to
      opacity: 0

    .text
      display: flex
      flex-direction: column
      justify-content: center
      flex: 1
      line-height: 20px
      overflow: hidden
      .name
        margin-bottom: 2px
        no-wrap()
        font-size: $font-size-medium
        color: $color-text
      .desc
        no-wrap()
        font-size: $font-size-small
        color: $color-text-d
    .control
      flex: 0 0 30px
      width: 30px
      padding: 0 10px
      .icon-play-mini, .icon-pause-mini, .icon-playlist
        font-size: 30px
        color: $color-theme-d
      .icon-mini
        font-size: 32px
        position: absolute
        left: 0
        top: 0

@keyframes rotate
  0%
    transform: rotate(0)
  100%
    transform: rotate(360deg)

</style>
